<?php
namespace app\admin\controller;

use app\common\model\admin\AdminMenu;
use app\common\controller\Tree;
use think\Loader;
use think\Exception;
use think\Db;
use app\common\controller\Log;

class Menu extends Base
{

	/**
	 * 获取菜单列表
	 * @return unknown
	 */
	public function index()
	{
		$list = AdminMenu::where(['state' => 1])->select()->toArray();
		
		//替换数组数据
		foreach ($list as &$rows) {
			$rows['label'] = $rows['menu_name'];
		}
		
		$tree = new Tree();
		$list = $tree->setTree($list,'parent_id','children');
		foreach ($list as &$row){
			sort($row['children']);
		}
		sort($list);
		return jsonSuccess($list);
	}
	/**
	 * 系统目录添加、修改
	 * @throws Exception
	 * @return unknown
	 */
	public function menuSet()
	{
		//获取客户端传递的数据
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//场景验证数据合法性
			$validate = Loader::validate('Menus');
			if(!$validate->scene('add')->check($data))
				throw new Exception($validate->getError());
			//判断操作方式添加还是删除0添加，1修改
			$style = $data['set_state'];
			unset($data['set_state']);
			if($style) {
				$data['update_time'] = time();
				AdminMenu::where(['id' => $data['id']])->update($data);
			}else{
				unset($data['id']);
				$data['create_time'] = time();
				$data['update_time'] = time();
				AdminMenu::create($data);
			}
			//添加管理员操作日志
			$log_msg = !$style ? '添加菜单【'.$data['menu_name'].'】' : '修改菜单【'.$data['menu_name'].'】';
			$style = $style ? 2 : 1;
			Log::addLog($style, $log_msg);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('提交成功');
	}
	
	/**
	 * 删除菜单
	 * @throws Exception
	 * @return unknown
	 */
	public function menuDelete()
	{
		//获取客户端传递的数据
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$menu = AdminMenu::get($id);
			if(!$menu->state)throw new Exception('系统错误');
			//初始化要删除的所有菜单数组
			$child_id = $menu -> parent_id ? [] : AdminMenu::where(['parent_id' => $id])->column('id');
			$child_id[] = $id;
			//删除当前菜单和所有下级子菜单
			AdminMenu::where(['id' => ['in',$child_id],'state' => 1])->update(['state' => 0]);
			//获取全部名称
			$menu_names = AdminMenu::where(['id' => ['in',$child_id]])->column('menu_name');
			//添加操作日志
			foreach ($menu_names as $rows) {
				Log::addLog(3, "删除菜单【{$rows}】");
			}
			Db::commit();
		}catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}

	
}